var hercule = require('hercule')
var utils = require('./utils/utils')
var fs = require('fs')
function getFileStr() {
    var _files = fs.readdirSync("./controllers");
    _files = utils.MyMap(_files, item => item = "./controllers/" + item)
    return _files
}

function getObjects() {
    var _files = fs.readdirSync("./objects");
    _files = utils.MyMap(_files, item => item = "./objects/" + item)
    _files = utils.mergeArray(["./z_dataStructures.apib"], _files)
    return _files
}
function getHeaderFile() {
    return ["./a_header.apib"]
}

function set_IndexApi() {
    var _files = utils.mergeArray(getHeaderFile(), getFileStr())
    _files = utils.mergeArray(_files, getObjects())
    var fileStr = ""
    for (var i = 0; i < _files.length; i++) {
        var file = _files[i]
        var _content = `:[${file.slice(2, file.length)}](${file})\n    \n`
        fileStr += _content
    }
    fs.writeFileSync("./_index.apib", fileStr)

}
function changeEvent() {
    set_IndexApi()
    hercule.transcludeFile("./_index.apib", (err, output) => {
        if (err) console.log(err)
        // console.log(output);
        fs.writeFileSync("./index.apib", output)

        var aglio = require('aglio')
        aglio.render(fs.readFileSync('./index.apib', 'utf-8'), {}, function (err, html, warnings) {
            // if (err) return console.log(err);
            // if (warnings) console.log(warnings);
            console.log("index.html create done");
            fs.writeFileSync("./views/index.html", html)
        });

    });
}


var chokidar = require('chokidar');
var watcher = chokidar.watch(['controllers', "objects"], {
    ignored: /(^|[\/\\])\../,
    persistent: true
});
watcher.on('change', path => {
    console.log(`File ${path} has been changed`)
    changeEvent()
})

changeEvent()

var express = require('express')
var app = express()
app.use(express.static('./views'))
app.listen("9000")
console.log("html in  9000")

